package com.inspur.edp.web.relycheck.dependencygenerator;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.spi.entity.MetadataElementDependencyDetail;
import com.inspur.edp.web.common.utility.ListUtility;

import com.inspur.edp.web.formmetadata.metadata.formdom.FormDOM;
import com.inspur.edp.web.relycheck.constant.RelyCheckType;
import com.inspur.edp.web.relycheck.dependencygenerator.entity.SourceElementField;
import com.inspur.edp.web.relycheck.elements.CustomField;
import com.inspur.edp.web.relycheck.elements.CustomEntity;


import java.util.ArrayList;
import java.util.List;

/**
 * schema 字段依赖信息构造
 *
 * @author noah
 */
public class SchemaFieldDependencyGenerator {

    private final RelyCheckType fieldRelyCheckType = RelyCheckType.SchemaField;

    /**
     * 构造字段列表对应的依赖信息
     *
     * @param fieldList schema 中的字段信息列表
     * @return
     */
    public List<MetadataElementDependencyDetail> generateDependencyDetailWithSchemaFieldList(CustomEntity schemaCustomEntity, List<CustomField> fieldList, FormDOM formDOM, GspMetadata gspMetadata) {
        if (ListUtility.isEmpty(fieldList)) {
            return new ArrayList<>(0);
        }

        List<MetadataElementDependencyDetail> metadataElementDependencyDetailList = new ArrayList<>();

        fieldList.forEach(fieldItem -> {
            // 从字段中构造对应的依赖信息
            MetadataElementDependencyDetail metadataElementDependencyDetail = this.generateDependencyDetailWithSchemaField(schemaCustomEntity, fieldItem, formDOM, gspMetadata);
            ListUtility.add(metadataElementDependencyDetailList, metadataElementDependencyDetail);
        });
        return metadataElementDependencyDetailList;
    }

    /**
     * 构造的是字段的依赖信息
     *
     * @param fieldItem 传递的表单schema中美
     * @return
     */
    private MetadataElementDependencyDetail generateDependencyDetailWithSchemaField(CustomEntity schemaCustomEntity, CustomField fieldItem, FormDOM formDOM, GspMetadata gspMetadata) {
        if (fieldItem == null) {
            return null;
        }
        MetadataElementDependencyDetail dependencyDetail = new MetadataElementDependencyDetail();

        SourceElementField sourceElementField = SourceElementField.init(schemaCustomEntity, fieldItem, formDOM, gspMetadata);

        dependencyDetail.setSourceElement(MetadataElementGenerator.generate(fieldRelyCheckType, sourceElementField));
        dependencyDetail.setReferenceType(fieldRelyCheckType.getReferenceType());
        dependencyDetail.setTargetElementLocator(MetadataVOElementLocatorGenerator.generate(
                () -> schemaCustomEntity.getId() + "/" + fieldItem.getId(),
                () -> fieldRelyCheckType.getReferenceType()

        ));

        return dependencyDetail;
    }
}
